package com.hn.vue.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * hanni
 * 2019/3/6 0006
 * 19:06
 *
 */
//@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Map<String, Object> objectMap = null;
        try{
            //查询用户，返回唯一的一条数据
            objectMap = jdbcTemplate.queryForMap("select * from sys_user where name = ?", username);
        }catch (Exception e){
            throw new UsernameNotFoundException("账号不存在......");
        }

        List<GrantedAuthority> authorityList  =new ArrayList<>();
        String sql = "SELECT p.perms FROM `sys_permission` p LEFT JOIN  sys_role_permission rp\n" +
                "on rp.permssion_id = p.id LEFT JOIN sys_role r on rp.role_id = r.id left join sys_user_role ur on ur.role_id = r.id where ur.user_id = ?";
        List<String> stringList = jdbcTemplate.queryForList(sql, String.class,objectMap.get("id"));

        System.out.println(stringList);
        if (stringList != null && stringList.size()>0){
            stringList.stream().forEach(a->authorityList.add(new SimpleGrantedAuthority(a)));
        }

//        User user = new User(objectMap.get("name").toString(),objectMap.get("password").toString(),Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
        User user = new User(objectMap.get("name").toString(),objectMap.get("password").toString(),authorityList);

        return user;
    }
}
